﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;
using System.Collections;

namespace CitrixPVSWrapper
{

    [System.Management.Automation.Cmdlet("Run", "PvsDiskUpdateStart", SupportsShouldProcess = true)]
    public class Run_PvsDiskUpdateStart : System.Management.Automation.PSCmdlet
    {

        [Parameter(ParameterSetName = "UpdateTask", Mandatory = true)]
        public PvsUpdateTask UpdateTask;

        [Parameter(ParameterSetName = "UpdateTaskId", ValueFromPipelineByPropertyName = true, Mandatory = true)]
        [Alias("Id")]
        public string UpdateTaskId;

        [Parameter(ParameterSetName = "UpdateTaskName", Mandatory = true)]
        [Parameter(ParameterSetName = "UpdateTaskName-SiteName", Mandatory = true)]
        [Parameter(ParameterSetName = "UpdateTaskName-SiteId", Mandatory = true)]
        [Parameter(ParameterSetName = "UpdateTaskName-Site", Mandatory = true)]
        [Alias("Name")]
        public string UpdateTaskName;

        [Parameter(ParameterSetName = "UpdateTaskName-Site", Mandatory = true)]
        public PvsSite Site;

        [Parameter(ParameterSetName = "UpdateTaskName-SiteId", Mandatory = true)]
        public string SiteId;

        [Parameter(ParameterSetName = "UpdateTaskName-SiteName", Mandatory = true)]
        public string SiteName;

        protected override void ProcessRecord()
        {
            // Verbose and Debug Settings
            Boolean Verbose = this.MyInvocation.BoundParameters.ContainsKey("Verbose");
            WriteVerbose("Verbose Flag: " + Verbose);
            Boolean Debug = this.MyInvocation.BoundParameters.ContainsKey("Debug");
            WriteDebug("Debug Flag: " + Debug);

            // UpdateTasks to hold the queries and the results
            Collection<QueryDefinition> RunQueries = new Collection<QueryDefinition>();
            string TargetObject = "DiskUpdateStart";

            // Build the queries based on the parameter sets
            switch (this.ParameterSetName)
            {
                case "UpdateTask":
                    {
                        RunQueries.Add(new QueryDefinition(QueryActionType.Run, TargetObject, "UpdateTaskId=\"" + this.UpdateTask.UpdateTaskId + "\""));
                        break;
                    }

                case "UpdateTaskId":
                    {
                        RunQueries.Add(new QueryDefinition(QueryActionType.Run, TargetObject, "UpdateTaskId=\"" + this.UpdateTaskId + "\""));
                        break;
                    }

                case "UpdateTaskName":
                    {
                        foreach (PvsUpdateTask QryUpdateTask in Get_PvsUpdateTask_Internal.Get_UpdateTaskByName(this.UpdateTaskName, Verbose))
                        { RunQueries.Add(new QueryDefinition(QueryActionType.Run, TargetObject, "UpdateTaskId=\"" + QryUpdateTask.UpdateTaskId + "\"")); }
                        break;
                    }

                case "UpdateTaskName-Site":
                    {
                        foreach (PvsUpdateTask QryUpdateTask in Get_PvsUpdateTask_Internal.Get_UpdateTaskByNameAndSiteId(this.UpdateTaskName, this.Site.SiteId, Verbose))
                        { RunQueries.Add(new QueryDefinition(QueryActionType.Run, TargetObject, "UpdateTaskId=\"" + QryUpdateTask.UpdateTaskId + "\"")); }
                        break;
                    }

                case "UpdateTaskName-SiteId":
                    {
                        foreach (PvsUpdateTask QryUpdateTask in Get_PvsUpdateTask_Internal.Get_UpdateTaskByNameAndSiteId(this.UpdateTaskName, this.SiteId, Verbose))
                        { RunQueries.Add(new QueryDefinition(QueryActionType.Run, TargetObject, "UpdateTaskId=\"" + QryUpdateTask.UpdateTaskId + "\"")); }
                        break;
                    }

                case "UpdateTaskName-SiteName":
                    {
                        foreach (PvsUpdateTask QryUpdateTask in Get_PvsUpdateTask_Internal.Get_UpdateTaskByNameAndSiteName(this.UpdateTaskName, this.SiteName, Verbose))
                        { RunQueries.Add(new QueryDefinition(QueryActionType.Run, TargetObject, "UpdateTaskId=\"" + QryUpdateTask.UpdateTaskId + "\"")); }
                        break;
                    }

            }

            // Test that we have a suitable object to perform the Run with, and build the confirmation message
            if (RunQueries.Count() == 0)
            {
                WriteError(new ErrorRecord(new InvalidOperationException("No items were found to start a disk update on using the supplied parameters"), "1", ErrorCategory.InvalidArgument, null));
            }

            // Execute the run queries
            foreach (QueryDefinition RunQuery in RunQueries)
            {

                string objectId;
                string objectName;
                string ShouldProcessMessage;

                // Check that we have a valid parameter to work with, extract the object id/name and build the ShouldProcess message
                if (RunQuery.Parameters.Where(p => p.StartsWith("UpdateTaskId")).Count() == 1)
                {
                    objectId = RunQuery.Parameters.Where(p => p.StartsWith("UpdateTaskId")).First().Split('=')[1].Replace('"', ' ').Trim();
                    if (Get_PvsUpdateTask_Internal.Get_UpdateTaskById(objectId).Count() != 1)
                    {
                        WriteError(new ErrorRecord(new InvalidOperationException(String.Format("Update task Id {0} does not exist", objectId)), "2", ErrorCategory.InvalidArgument, null));
                        continue;
                    }
                    objectName = Get_PvsUpdateTask_Internal.Get_UpdateTaskById(objectId).First().UpdateTaskName;
                    ShouldProcessMessage = String.Format("Start update task {0} with update task Id {1}", objectName, objectId);
                }

                else
                {
                    WriteError(new ErrorRecord(new InvalidOperationException("Query does not contain any valid targets"), "2", ErrorCategory.InvalidArgument, null));
                    continue;
                }

                // Perform the actual run and return any errors
                if (ShouldProcess(ShouldProcessMessage))
                {
                    MCliReturnObject Return = PvsHelpers.ExecuteMcliAction(RunQuery, Verbose, Debug);
                    if (Return.ReturnState == ReturnState.Error) { foreach (ErrorRecord Error in Return.Errors) { WriteError(Error); } }
                }

            }

        }
    }
}
